package com.sm.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.sm.model.User;
import com.sm.model.UserBankCard;
import com.sm.model.Withdrawal;
import com.sm.service.UserBankCardService;
import com.sm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sm.service.WithdrawalService;
import com.sm.util.Msg;

@Controller
@RequestMapping("/withdrawal")
public class WithdrawalController {

    @Autowired
    private WithdrawalService withdrawalService;
    @Autowired
    private UserBankCardService userBankCardService;
    @Autowired
    private UserService userService;

    /**
     * 获取用户提现记录
     *
     * @param userId
     * @return
     */
    @RequestMapping("/getWithdrawalByUserId")
    @ResponseBody
    public Msg getWithdrawalByUserId(@RequestParam("userId") Integer userId) {
        if (userId == null) {
            return Msg.fail().add("msg", "参数不为空！");
        }
        List<Withdrawal> list = withdrawalService.selectByUserId(userId);
        return Msg.success().add("list", list);
    }

    /**
     * 添加提现记录
     *
     * @param recode
     * @return
     */
    @RequestMapping("/insertSelective")
    @ResponseBody
    public Msg insertSelective(Withdrawal recode) {
        User user = userService.selectUserById(recode.getUserId());
        UserBankCard userBankCard = userBankCardService.selectAll(user.getUserId());
        if (recode.getWithdrawalMoney().compareTo(new BigDecimal(100)) < 0) {
            return Msg.fail().add("msg", "提现金额不能小于100！");
        }
        if (StrUtil.isEmpty(userBankCard.getBankCard())) {
            return Msg.fail().add("msg", "银行卡不存在！");
        } else if (recode.getWithdrawalMoney().compareTo(BigDecimal.valueOf(user.getBalance()))>0) {
            return Msg.fail().add("msg", "账户余额不足");
        }
        recode.setBankCardId(userBankCard.getBankCardId());
        recode.setCreateTime(new Date());
        recode.setUpdateTime(new Date());
        //手续费
        BigDecimal charge = recode.getWithdrawalMoney().multiply(new BigDecimal("0.07")).setScale(2, RoundingMode.HALF_UP);
        recode.setCharge(charge);
        recode.setRealMoney(recode.getWithdrawalMoney().subtract(charge));
        int i = withdrawalService.insertSelective(recode);
        if (i == 1) {
            Double balance = user.getBalance();
            balance = balance - recode.getWithdrawalMoney().doubleValue();
            user.setBalance(balance);
            userService.updateByPrimaryKeySelective(user);
            return Msg.success().add("msg", "提现申请已提交");
        }

        return Msg.fail();
    }


}
